package com.mid;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * Created by Lxk on 2020/1/11.
 */
public class Solution515 {

    public List<Integer> largestValues(TreeNode root) {
        Queue<TreeNode> nodeQueue = new LinkedList<>();
        List<Integer> res = new ArrayList<>();
        if (root != null) {
            nodeQueue.add(root);
            res.add(root.val);
        }
        TreeNode head = root;
        TreeNode tail = null;
        while (!nodeQueue.isEmpty()) {
            TreeNode cur = nodeQueue.poll();
            if (cur.left != null) {
                nodeQueue.add(cur.left);
                tail = cur.left;
            }
            if (cur.right != null) {
                nodeQueue.add(cur.right);
                tail = cur.right;
            }
            if (cur == head) {
                head = tail;
                Integer max = Integer.MIN_VALUE;
                boolean flag = false;
                for (TreeNode treeNode : nodeQueue) {
                    if (max <= treeNode.val) {
                        max = treeNode.val;
                        flag = true;
                    }
                }
                if (flag) {
                    res.add(max);
                }
            }
        }
        return res;
    }

}
